/*
 * @Author: C.
 * @Date: 2023-01-30 16:56:03
 */
import { ref, onMounted, onUnmounted } from 'vue';
interface IProps {
  designHeight?: number;
  designWidth?: number;
  resize?: boolean;
}
/**
 * @description: { designHeight 设计图高度, designWidth 设计图宽度, resize 是否自动适应 }
 * @param {IProps} { designHeight = 1080, designWidth = 1920, resize = true }
 * @return {*}
 */
export function useWindowFit({ designHeight = 1080, designWidth = 1920, resize = true }: IProps) {
  // * 指向最外层容器
  const screenRef = ref();
  // * 定时函数
  const timer = ref(0);
  // * 默认缩放值
  const scale = {
    width: '1',
    height: '1',
  };
  // * 设计稿尺寸（px）
  const baseWidth = designWidth;
  const baseHeight = designHeight;

  // * 需保持的比例（默认1.77778）
  const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));
  const calcRate = () => {
    // 当前宽高比
    const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5));
    if (screenRef.value) {
      if (currentRate > baseProportion) {
        // 表示更宽
        scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5);
        scale.height = (window.innerHeight / baseHeight).toFixed(5);
        screenRef.value.style.transform = `scale(${scale.width}, ${scale.height})`;
      } else {
        // 表示更高
        scale.height = (window.innerWidth / baseProportion / baseHeight).toFixed(5);
        scale.width = (window.innerWidth / baseWidth).toFixed(5);
        screenRef.value.style.transform = `scale(${scale.width}, ${scale.height})`;
      }
    }
  };

  const toResize = () => {
    clearTimeout(timer.value);
    timer.value = window.setTimeout(() => {
      calcRate();
    }, 200);
  };

  // 改变窗口大小重新绘制
  const windowDraw = () => {
    if (!resize) return;
    window.addEventListener('resize', toResize);
  };

  // 移除变化监听
  const unWindowDraw = () => {
    if (!resize) return;

    window.removeEventListener('resize', toResize);
  };
  onMounted(() => {
    // 监听浏览器窗口尺寸变化
    windowDraw();
    calcRate();
  });

  onUnmounted(() => {
    unWindowDraw();
  });

  return {
    screenRef,
    calcRate,
    windowDraw,
    unWindowDraw,
  };
}
